import { getDB } from '../db/connection.js';

class Component {
  static async getAll() {
    try {
      const db = await getDB();
      const [rows] = await db.execute('SELECT * FROM components');
      return rows;
    } catch (error) {
      throw new Error(`Error fetching components: ${error.message}`);
    }
  }

  static async getById(id) {
    const db = getDB();  // 移除await
    const [rows] = await db.execute('SELECT * FROM components WHERE id = ?', [id]);
    return rows.length > 0 ? rows[0] : null;
  }

  static async getByName(name) {
    const db = getDB();  // 移除await
    const [rows] = await db.execute('SELECT * FROM components WHERE name = ?', [name]);
    return rows.length > 0 ? rows[0] : null;
  }

  static async create(name, description) {
    const db = getDB();  // 移除await
    const [result] = await db.execute(
      'INSERT INTO components (name, description) VALUES (?, ?)',
      [name, description]
    );
    return result.insertId;
  }

  static async update(id, data) {
    const db = getDB();  // 移除await
    const fields = Object.keys(data);
    const values = Object.values(data);
    const setClause = fields.map(field => `${field} = ?`).join(', ');
    
    await db.execute(
      `UPDATE components SET ${setClause} WHERE id = ?`,
      [...values, id]
    );
    
    return this.getById(id);
  }

  static async delete(id) {
    const db = getDB();  // 移除await
    await db.execute('DELETE FROM components WHERE id = ?', [id]);
  }
}

export default Component;